import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
// import { resetRouter } from '@/router'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 5000 // request timeout
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    if (!config.headers.Authorization && store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const { message, success } = response.data
    // if (success) {
    //   return response.data
    // } else {
    //   Message.error(message)
    //   return Promise.reject(message)
    // }

    !success && Message.error(message)
    return success ? response.data : Promise.reject(message)
  },
  error => {
    try {
      const status = error.response.status
      status === 401 && store.commit('user/REMOVE_USERINFO') && router.push('/login')
      // if (status === 401) {
      //   store.commit('user/REMOVE_TOKEN')
      //   router.push('/login')
      //   resetRouter()
      // }

      return Promise.reject(error)
    } catch (err) {
      return Promise.reject(err)
    }
  }
)

export default request
